// Copyright -2011 Google Inc. All Rights Reserved.

package google.usingblobstore;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

/**
 * Performs calculations on scores using Datastore.
 * 
 * @author eschoeffler@google.com (Eric Schoeffler)
 */
public class DatastoreScoreCalculator implements ScoreCalculator {
  
  private DatastoreService datastore;
  
  public DatastoreScoreCalculator() {
    datastore = DatastoreServiceFactory.getDatastoreService();
  }
  
  @Override
  public ScoresData averageByHair(String hairColor) {
    Query q = new Query("Person");
    if (!(hairColor == null || hairColor.trim().length() == 0)) {
      q.addFilter("hair_color", Query.FilterOperator.EQUAL, hairColor);
    }
    PreparedQuery pq = datastore.prepare(q);
    int count = 0;
    long score = 0;
    long start = System.currentTimeMillis();
    for (Entity result : pq.asIterable()) {
      if (hairColor == null || hairColor.trim().length() == 0 || result.getProperty("hair_color").equals(hairColor)) {
        score += (Long) result.getProperty("test_score");
        count ++;
      }
    }
    long elapsed = System.currentTimeMillis() - start;
    return new ScoresData(elapsed / 1000.0, count, count == 0 ? 0 : (int) (score / count));
  }

}
